<?php

namespace App\Service;


use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class QiNiuService
{
    public static function image($img, $prefix = null)
    {
        // 把文件存到qiniu
        $disk = Storage::disk('qiniu');
        if (!$prefix) {
            $prefix = env('APP_NAME');
        }
        $path = $prefix . '/' . date('Ymd') . '/' . uniqid() . '.png';
        $res = $disk->put($path, $img);
        $url = '';
        if ($res) {
            $url = 'https://' . config('filesystems.disks.qiniu.domain') . '/' . $path;
        }
        return ['status' => $res, 'url' => $url];
    }

    public static function imageFileObject(Request $request)
    {
        $image = $request->file('image');
        $prefix = $request->input('prefix', env('APP_NAME'));
        if (!$prefix) {
            $prefix = env('APP_NAME');
        }
        $disk = Storage::disk('qiniu');
        $path = $prefix . '/' . date('Ymd') . '/' . uniqid() . '.png';
        $res = $disk->put($path, file_get_contents($image->getRealPath()));
        $url = '';
        if ($res) {
            $url = 'https://' . config('filesystems.disks.qiniu.domain') . '/' . $path;
        }
        return ['status' => $res, 'url' => $url];
    }

    public static function imageFileArray($image, Request $request, $type)
    {
//        dd($image);
        $prefix = $request->input('prefix', env('APP_NAME'));
        if (!$prefix) {
            $prefix = env('APP_NAME');
        }
        $disk = Storage::disk('qiniu');
        $path = $prefix . '/' . $type . '/' . date('Ymd') . '/' . uniqid() . '.png';
        $res = $disk->put($path, file_get_contents($image->getRealPath()));
        $url = '';
        if ($res) {
            $url = 'http://' . config('filesystems.disks.qiniu.domain') . '/' . $path;
        }
        return $url;
    }

    public static function base64ToImage($fileStr, $type = 'png')
    {
        $base64Data = preg_replace('/^data:image\/(png|jpg);base64,/', '', $fileStr);
        $img = base64_decode($base64Data);
        return $img;
    }
}
